#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Charles.chen
# createDate:2017/9/30
# Title: mqtt 单例模式
# Tip:
import paho.mqtt.client as mqtt


class MqttSingle(object):
    _instance = None
    client = None

    def __init__(self):
        if MqttSingle.client is None:
            MqttSingle.client = initMqtt()
            pass
        pass

    def __new__(cls, *args, **kwargs):
        if MqttSingle._instance is None:
            MqttSingle._instance = object.__new__(cls, *args, **kwargs)
        return MqttSingle._instance

    pass

def initMqtt():
    ip = "10.2.0.135"
    port = 61613
    client = mqtt.Client("uniqu3eid")
    # 参数有 Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
    client.username_pw_set("admin", "password")  # 必须设置，否则会返回「Connected with result code 4」
    client.on_connect = on_connect  # 设置连接上服务器回调函数
    client.on_message = on_message  # 设置接收到服务器消息回调函数
    client.connect(ip, port, 60)  # 连接服务器,端口为61613,维持心跳为60秒
    client.loop_forever()
    return client

# 当连接上服务器后回调此函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    # 放在on_connect函数里意味着
    # 重新连接时订阅主题将会被更新
    client.subscribe("toclient/124", 2)

# 从服务器接受到消息后回调此函数
def on_message(client, userdata, msg):
    print("主题:" + msg.topic + " 消息:" + str(msg.payload)+" Qos:" + str(msg.qos))



if __name__ == '__main__':
    mqttObj1 = MqttSingle()
    mqttObj2 = MqttSingle()
    print id(mqttObj1.client)
    print id(mqttObj2.client)
    pass